﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.PermissionManagement.IPermissionManagement;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Query.PermissionManagement.DepartmentInfo;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Query.PermissionManagement.BaseQuery;
using SportsPlatform.Dto.PermissionManagement.DepartmentInfo;
using Abp.Application.Services;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;
using Abp.Domain.Repositories;
using Abp.Collections.Extensions;

namespace SportsPlatform.PermissionManagement.PermissionManagement
{
    /// <summary>
    /// 部门架构表
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class DepartmentInfoService :SportsPlatformAppServiceBase, IDepartmentInfoService
    {
        private readonly IRepository<DepartmentInfo, Guid> _depRepository;
        public DepartmentInfoService(IRepository<DepartmentInfo, Guid> depRepository,IHttpContextAccessor context) : base(context)
        {
            _depRepository = depRepository;
        }
        /// <summary>
        /// 新增信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddDepartmentInfo(AddDepartmentInfoQuery query)
        {
            BaseResultDto resultDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var departmentInfo = ObjectMapper.Map<DepartmentInfo>(query);
                departmentInfo.States = true;
                departmentInfo.CreateTime = DateTime.Now;
                departmentInfo.CreateUserId = token.Id;
                departmentInfo.CompanyId = (Guid)(query.CompanyId == null ? token.CompanyId : query.CompanyId);
                await _depRepository.InsertAsync(departmentInfo);
                resultDto.IsSuccess = true;
                resultDto.Code = HttpResultCode.Success;
                resultDto.Message = "操作成功！";
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }
        /// <summary>
        /// 根据Id删除
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> DeleteDepartmentInfo(DeleteOrGetModelQuery query)
        {
            BaseResultDto resultDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var depinfo = await _depRepository.FirstOrDefaultAsync(query.Id);
                if (depinfo != null)
                {
                    depinfo.IsDeleted = true;
                    depinfo.DeleteTime = DateTime.Now;
                    depinfo.DeleteUserId=token.Id;
                    await _depRepository.UpdateAsync(depinfo);
                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.Message = "删除成功！";
                
                }
                else {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.Message = "未查到要删除的数据！";
                }

            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 根据Id获取信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetDepartmentInfoDto>> GetDepartmentInfo(DeleteOrGetModelQuery query)
        {
            ResultDto<GetDepartmentInfoDto> resultDto = new();
            try
            {
               var depinfo = await _depRepository.FirstOrDefaultAsync(query.Id);
                if (depinfo != null)
                {
                    resultDto.IsSuccess = true;
                    resultDto.Code=HttpResultCode.Success;
                    resultDto.Message = "查询成功！";
                    resultDto.Data = ObjectMapper.Map<GetDepartmentInfoDto>(depinfo);
                }
                else {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.Message = "未查询到数据！";
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取所有上级List
        /// </summary>
        /// <param name="getDepartmentInfoTreeQuery"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetDepartmentInfoTreeDto>> GetDepartmentInfoParentList(GetDepartmentInfoTreeQuery getDepartmentInfoTreeQuery)
        {
            ResultListDto<GetDepartmentInfoTreeDto> resultListDto = new ResultListDto<GetDepartmentInfoTreeDto>();
            resultListDto.Code = HttpResultCode.SqlError;
            try
            {
                //var departmentinfolist = await _sugar.Queryable<DepartmentInfo>().ToParentListAsync(info => info.ParentId, getDepartmentInfoTreeQuery.ParentId);
                //if (departmentinfolist != null && departmentinfolist.Count > 0)
                //{
                //    resultListDto.Code = HttpResultCode.Success;
                //    resultListDto.Count = departmentinfolist.Count;
                //    List<GetDepartmentInfoTreeDto> getDepartmentInfoTreeDtos = new List<GetDepartmentInfoTreeDto>();
                //    departmentinfolist.ForEach(info =>
                //    {
                //        getDepartmentInfoTreeDtos.Add(_mapper.Map<GetDepartmentInfoTreeDto>(info));
                //    });
                //    resultListDto.Data = getDepartmentInfoTreeDtos;
                //}
            }
            catch (Exception e)
            {
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }

        /// <summary>
        /// 获取所有下级List
        /// </summary>
        /// <param name="getDepartmentInfoTreeQuery"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetDepartmentInfoTreeDto>> GetDepartmentInfoChildList(GetDepartmentInfoTreeQuery getDepartmentInfoTreeQuery)
        {
            ResultListDto<GetDepartmentInfoTreeDto> resultListDto = new ResultListDto<GetDepartmentInfoTreeDto>();
            //resultListDto.Code = HttpResultCode.SqlError;
            //try
            //{
            //    var departmentinfolist = await _sugar.Queryable<DepartmentInfo>().ToTreeAsync(info => info.DepartmenList, info => info.ParentId, getDepartmentInfoTreeQuery.ParentId);

            //    if (departmentinfolist != null && departmentinfolist.Count > 0)
            //    {
            //        resultListDto.Code = HttpResultCode.Success;
            //        resultListDto.Count = departmentinfolist.Count;
            //        List<GetDepartmentInfoTreeDto> getDepartmentInfoTreeDtos = new List<GetDepartmentInfoTreeDto>();
            //        departmentinfolist.ForEach(info =>
            //        {
            //            getDepartmentInfoTreeDtos.Add(_mapper.Map<GetDepartmentInfoTreeDto>(info));
            //        });
            //        resultListDto.Data = getDepartmentInfoTreeDtos;
            //    }
            //}
            //catch (Exception e)
            //{
            //    resultListDto.Code = HttpResultCode.Error;
            //    resultListDto.Message = e.Message.ToString();
            //}
            return resultListDto;
        }

        /// <summary>
        /// 获取信息List
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetDepartmentInfoDto>> GetDepartmentInfoList(GetDepartmentInfoQuery query)
        {
            ResultListDto<GetDepartmentInfoDto> resultListDto = new();
            resultListDto.Code = HttpResultCode.SqlError;
            try
            {
                var departmentinfo = (await _depRepository.GetAllListAsync())
                        .WhereIf(!string.IsNullOrEmpty(query.DepartmentName), info => info.DepartmentName == query.DepartmentName)
                        .WhereIf(!string.IsNullOrEmpty(query.DepartmentLevel), info => info.DepartmentLevel == query.DepartmentLevel)
                        .WhereIf(query.DepartmentSeq != null, info => info.DepartmentSeq == query.DepartmentSeq)
                        .WhereIf(query.ParentId != null, info => info.ParentId == query.ParentId)
                        .WhereIf(query.States != null, info => info.States == query.States)
                        .WhereIf(query.CompanyId != null, info => info.CompanyId == query.CompanyId)
                        .WhereIf(query.States != null, info => info.States == query.States)
                        .OrderByDescending(info => info.CreateTime)
                        .ToList();
                if (departmentinfo != null && departmentinfo.Count > 0)
                {
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = ObjectMapper.Map<List<GetDepartmentInfoDto>>(departmentinfo);
                }
                else {
                    resultListDto.IsSuccess = false;
                    resultListDto.Code = HttpResultCode.NotData;
                    resultListDto.Message = "未查询到数据！";
                }
            }
            catch (Exception e)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }

        /// <summary>
        /// 状态更改
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> IsStatesDepartmentInfo(IsStatesdModel query)
        {
            BaseResultDto baseResultDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var depinfo = await _depRepository.FirstOrDefaultAsync(query.Id);
                if (depinfo != null)
                {
                    depinfo.States = query.States;
                    depinfo.UpdateTime = DateTime.Now;
                    depinfo.UpdateUserId = token.Id;
                    await _depRepository.UpdateAsync(depinfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更改成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.NotData;
                    baseResultDto.Message = "未查询到数据！";
                }
               
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateDepartmentInfo(UpdateDepartmentInfoQuery query)
        {
            BaseResultDto baseResultDto=new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var depinfo = await _depRepository.FirstOrDefaultAsync(query.Id);
                if (depinfo != null)
                {
                    depinfo.UpdateTime = DateTime.Now;
                    depinfo.UpdateUserId = token.Id;
                    if (query.States != null)
                    {
                        depinfo.States = (bool)query.States;
                    }
                    if (query.ParentId != null)
                    {
                        depinfo.ParentId = (Guid)query.ParentId;
                    }
                    if (query.CompanyId != null)
                    {
                        depinfo.CompanyId = (Guid)query.CompanyId;
                    }
                    if (query.DepartmentSeq != null)
                    {
                        depinfo.DepartmentSeq = (int)query.DepartmentSeq;
                    }
                    if (!string.IsNullOrEmpty(query.DepartmentName))
                    {
                        depinfo.DepartmentName = query.DepartmentName;
                    }
                    if (!string.IsNullOrEmpty(query.DepartmentLevel))
                    {
                        depinfo.DepartmentLevel = query.DepartmentLevel;
                    }
                    if (!string.IsNullOrEmpty(query.DepartmentDescribe))
                    {
                        depinfo.DepartmentDescribe = query.DepartmentDescribe;
                    }
                    await _depRepository.UpdateAsync(depinfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更改成功！";

                }
                else {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.NotData;
                    baseResultDto.Message = "未查询到数据！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }
    }
}
